<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧字典分类树 -->
      <el-col :span="6">
        <div class="dict-type-tree">
          <div class="tree-header">
            <span>字典分类</span>
            <el-button
              type="primary"
              size="mini"
              @click="handleAddType"
              v-hasPermi="['system:dict:type:add']"
            >新增</el-button>
          </div>
          <el-tree
            :data="dictTypeTree"
            :props="defaultProps"
            node-key="id"
            highlight-current
            @node-click="handleNodeClick"
            :expand-on-click-node="false"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  type="text"
                  size="mini"
                  @click.stop="() => handleUpdateType(data)"
                  v-hasPermi="['system:dict:type:edit']"
                >修改</el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click.stop="() => handleDeleteType(data)"
                  v-hasPermi="['system:dict:type:remove']"
                >删除</el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>

      <!-- 右侧字典数据列表 -->
      <el-col :span="18">
        <div class="dict-data-list">
          <el-form :model="dictDataQueryParams" ref="dictDataQueryForm" size="small" :inline="true">
            <el-form-item label="字典标签" prop="label">
              <el-input
                v-model="dictDataQueryParams.label"
                placeholder="请输入字典标签"
                clearable
                @keyup.enter.native="handleDictDataQuery"
              />
            </el-form-item>
            <el-form-item label="字典键值" prop="value">
              <el-input
                v-model="dictDataQueryParams.value"
                placeholder="请输入字典键值"
                clearable
                @keyup.enter.native="handleDictDataQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDictDataQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetDictDataQuery">重置</el-button>
              <el-button
                type="primary"
                size="mini"
                @click="handleAddData"
                v-hasPermi="['system:dict:add']"
              >新增字典</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="dictDataLoading" :data="dictDataList">
            <el-table-column label="字典标签" align="center" prop="label" />
            <el-table-column label="字典键值" align="center" prop="value" />
            <el-table-column label="字典排序" align="center" prop="sort" />
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                {{ scope.row.status==0 ? '正常' : '停用' }}
              </template>
            </el-table-column>
            <el-table-column label="是否默认" align="center" prop="defaultFlag">
              <template slot-scope="scope">
                {{ scope.row.defaultFlag ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdateData(scope.row)"
                  v-hasPermi="['system:dict:data:edit']"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteData(scope.row)"
                  v-hasPermi="['system:dict:data:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="dictDataTotal>0"
            :total="dictDataTotal"
            :page.sync="dictDataQueryParams.pageNum"
            :limit.sync="dictDataQueryParams.pageSize"
            @pagination="getDictDataList"
          />
        </div>
      </el-col>

      <el-dialog :title="typeTitle" :visible.sync="typeOpen" width="500px">
        <el-form :model="typeForm" ref="typeForm" :rules="typeRules" label-width="100px">
          <el-form-item label="分类名称" prop="name">
            <el-input v-model="typeForm.name" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="分类类型" prop="type">
            <el-input v-model="typeForm.type" placeholder="请输入分类类型" />
          </el-form-item>
          <el-form-item label="备注" prop="type">
            <el-input v-model="typeForm.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="typeCancel">取消</el-button>
          <el-button type="primary" @click="submitTypeForm">确定</el-button>
        </div>
      </el-dialog>

      <el-dialog :title="dataTitle" :visible.sync="dataOpen" width="500px">
        <el-form :model="dataForm" ref="dataForm" :rules="dataRules" label-width="100px">
          <el-form-item label="字典类型" prop="dictType">
            <el-input v-model="dataForm.dictType" placeholder="请输入字典类型"  readonly />
          </el-form-item>
          <el-form-item label="是否默认选中" prop="defaultFlag">
            <el-radio-group v-model="dataForm.defaultFlag">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="字典标签" prop="label">
            <el-input v-model="dataForm.label" placeholder="请输入字典标签" />
          </el-form-item>
          <el-form-item label="字典键值" prop="value">
            <el-input v-model="dataForm.value" placeholder="请输入字典键值" />
          </el-form-item>
          <el-form-item label="顺序号" prop="sort">
            <el-input v-model="dataForm.sort" placeholder="请输入顺序号" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dataCancel">取消</el-button>
          <el-button type="primary" @click="submitDataForm">确定</el-button>
        </div>
      </el-dialog>
    </el-row>
  </div>
</template>

<script>
import { listType, getType, addType, updateType, delType } from "@/api/erpsystem/type";
import { listData, getData, addData, updateData, delData } from "@/api/erpsystem/data";

export default {
  name: "Dict",
  data() {
    return {
      dataTitle: '', // 添加一个响应式的数据属性
      typeTitle: '', // 默认为空字符串或者根据需要设置为其他初始值
          typeRules: {
            name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
          }, // 初始化为空对象或者包含验证规则的对象
          dataRules: {
            label: [{ required: true, message: '请输入字典标签', trigger: 'blur' }],
          }, // 初始化为空对象或者包含验证规则的对象
      dict: null, // 初始化为 null
      dictTypeTree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dictDataList: [],
      dictDataLoading: false,
      dictDataTotal: 0,
      dictDataQueryParams: {
        pageNum: 1,
        pageSize: 10,
        dictType: undefined,
        label: undefined,
        value: undefined
      },
      typeForm: {
            id: null,
            name: null,
            type: null,
            status: 0,
            remark: null
      },
      dataForm: {
            id: null,
            dictType: null,
            label: null,
            value: null,
            sort: 0,
            status: 0,
            defaultFlag: 0,
            colorType: null,
            remark: null
      },
       typeOpen: false, // 控制字典分类表单的显示
       dataOpen: false, // 控制字典数据表单的显示
    };
  },
  computed: {
    dictTypeOptions() {
      return this.dict?.type?.sys_normal_disable || [];
    }
  },
  created() {
    this.getDictData();
    this.getDictTypeTree();
  },
  methods: {
    async getDictData() {
      try {
        const response = await listType(); // 假设这是获取字典数据的 API 调用
        this.dict = response.data;
      } catch (error) {
        console.error("Failed to load dict data:", error);
      }
    },
    async getDictTypeTree() {
      try {
        const response = await listType(); // 假设这是获取字典分类树的 API 调用
        this.dictTypeTree = this.buildTree(response.rows);
      } catch (error) {
        console.error("Failed to load dict type tree:", error);
      }
    },
    buildTree(data) {
      const map = {};
      const result = [];

      data.forEach(item => {
        map[item.id] = {
          ...item,
          children: []
        };
      });

      data.forEach(item => {
        const parent = map[item.parentId];
        if (parent) {
          parent.children.push(map[item.id]);
        } else {
          result.push(map[item.id]);
        }
      });

      return result;
    },
    handleNodeClick(data) {
      this.dictDataQueryParams.dictType = data.type;
      this.dictDataQueryParams.pageNum = 1; // 重置页码
      this.getDictDataList();
    },
    async getDictDataList() {
      this.dictDataLoading = true;
      try {
        const response = await listData(this.dictDataQueryParams);
        this.dictDataList = response.rows;
        this.dictDataTotal = response.total;
      } catch (error) {
        console.error("Failed to load dict data list:", error);
      } finally {
        this.dictDataLoading = false;
      }
    },

    /** 字典数据搜索 */
    handleDictDataQuery() {
      this.dictDataQueryParams.pageNum = 1;
      this.getDictDataList();
    },

    /** 重置字典数据搜索 */
    resetDictDataQuery() {
      this.resetForm("dictDataQueryForm");
      this.handleDictDataQuery();
    },

    /** 字典分类新增按钮操作 */
    handleAddType() {
      this.typeReset();
      this.typeOpen = true;
      this.typeTitle = "添加字典分类";
    },

    /** 字典分类修改按钮操作 */
    handleUpdateType(row) {
      this.typeReset();
      const id = row.id;
      getType(id).then(response => {
        this.typeForm = response.data;
        this.getDictTypeTree();
        this.typeOpen = true;
        this.typeTitle = "修改字典分类";
      });
    },

    /** 字典分类删除按钮操作 */
    handleDeleteType(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除字典分类编号为"' + id + '"的数据项？').then(() => {
        return delType(id);
      }).then(() => {
        this.getDictTypeTree();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 字典分类表单重置 */
    typeReset() {
      this.typeForm = {
        id: null,
        name: null,
        type: null,
        status: 0,
        remark: null
      };
      this.resetForm("typeForm");
    },

    /** 字典分类取消按钮 */
    typeCancel() {
      this.typeOpen = false;
      this.typeReset();
    },

    /** 提交字典分类表单 */
    submitTypeForm() {
      this.$refs["typeForm"].validate(valid => {
        if (valid) {
          if (this.typeForm.id != null) {
            updateType(this.typeForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.typeOpen = false;
              this.getDictTypeTree();
            });
          } else {
            addType(this.typeForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.typeOpen = false;
              this.getDictTypeTree();
            });
          }
        }
      });
    },

    /** 字典数据新增按钮操作 */
    handleAddData() {
          if (!this.dictDataQueryParams.dictType) {
            this.$modal.msgWarning("请先在左侧选择字典分类");
            return;
          }
          this.dataReset();
          this.dataForm.dictType = this.dictDataQueryParams.dictType;
          this.dataOpen = true;
          this.dataTitle = "添加字典数据"; // 使用响应式的数据属性
          // 设置默认选中状态为否
              this.dataForm.defaultFlag = '0';
        },

    /** 字典数据修改按钮操作 */
    handleUpdateData(row) {
          this.dataReset();
          const id = row.id;
          getData(id).then(response => {
            this.dataForm = response.data;
            this.dataOpen = true;
            this.dataTitle = "修改字典数据"; // 使用响应式的数据属性
            // 根据后端返回的数据设置默认选中状态
                  this.dataForm.defaultFlag = response.data.defaultFlag.toString();
          });
        },

    /** 字典数据删除按钮操作 */
    handleDeleteData(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除字典数据编号为"' + id + '"的数据项？').then(() => {
        return delData(id);
      }).then(() => {
        this.getDictDataList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 字典数据表单重置 */
    dataReset() {
      this.dataForm = {
        id: null,
        dictType: null,
        label: null,
        value: null,
        sort: 0,
        status: 0,
        defaultFlag: 0,
        colorType: null,
        remark: null
      };
      this.resetForm("dataForm");
    },

    /** 字典数据取消按钮 */
    dataCancel() {
      this.dataOpen = false;
      this.dataReset();
    },

    /** 提交字典数据表单 */
    submitDataForm() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.dataForm.defaultFlag = Number(this.dataForm.defaultFlag);  // 转换为数字
          if (this.dataForm.id != null) {
            updateData(this.dataForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dataOpen = false;
              this.getDictDataList();
            });
          } else {
            addData(this.dataForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dataOpen = false;
              this.getDictDataList();
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.dict-type-tree {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.dict-data-list {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
